package com.jp.knowledge.view.experience;

import android.app.Dialog;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.anarchy.classify.ClassifyView;
import com.anarchy.classify.simple.BaseSimpleAdapter;
import com.anarchy.classify.simple.SimpleAdapter;
import com.jp.knowledge.R;
import com.jp.knowledge.adapter.ExperienceAdapter;
import com.jp.knowledge.dialog.CommDialog;
import com.jp.knowledge.dialog.ExperienceSubDialog;
import com.jp.knowledge.model.experience.TiyanApps;
import com.jp.knowledge.my.util.MyUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 528787067@qq.com on 2017/2/2.
 */

public class ExperienceClassifyView extends ClassifyView implements ExperienceAdapter.SubDialogShowListener,
        ExperienceSubDialog.DialogActionDownListener, View.OnClickListener, ExperienceAdapter.AllItemCheckListener,
        ExperienceAdapter.SwitchToEditListener, ExperienceAdapter.IconClickListener, ExperienceAdapter.ActionHappenedListener {

    private ExperienceSubDialog subDialog;
    private View subContentView;
    private TextView subTitleContent;
    private EditText subTitleEdit;
    private ImageView subGroupDelete;
    private LinearLayout subEditView;
    private TextView subEditSelete;
    private TextView subEditRemove;
    private TextView subEditDelete;
    private RecyclerView subRecyclerView;

    private List<List<TiyanApps>> classifyData;
    private ExperienceAdapter classifyAdapter;
    private boolean isEdit;

    public ExperienceClassifyView(Context context) {
        super(context);
    }

    public ExperienceClassifyView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ExperienceClassifyView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public SimpleAdapter getAdapter(){
        return this.classifyAdapter;
    }

    public void setAdapter(List<List<TiyanApps>> classifyData) {
        setAdapter(new ExperienceAdapter(classifyData, getContext()));
    }

    @Override
    public void setAdapter(BaseSimpleAdapter baseSimpleAdapter) {
        super.setAdapter(baseSimpleAdapter);
        this.classifyAdapter = (ExperienceAdapter) baseSimpleAdapter;
        this.classifyData = this.classifyAdapter.getData();
        this.classifyAdapter.setSubDialogShowListener(this);
        this.classifyAdapter.setAllItemCheckListener(this);
        this.classifyAdapter.setSwitchToEditListener(this);
        this.classifyAdapter.setIconClickListener(this);
        this.classifyAdapter.setActionHappenedListener(this);
    }

    public void notifyDataSetChanged(){
        if(this.classifyAdapter != null)
            this.classifyAdapter.notifyDataSetChanged();
        if(this.notifyDataSetChangedListener != null)
            this.notifyDataSetChangedListener.onDataSetChanged(classifyData);
    }

    public void setEdit(boolean isEdit){
        this.isEdit = isEdit;
        if(isEdit) {
            for (List<TiyanApps> group : classifyData)
                for (TiyanApps apps : group)
                    apps.setIsCheck(false);
        }
        if(this.editStateChangeListener != null)
            this.editStateChangeListener.onEditStateChange(isEdit);
        if(this.subDialog != null)
            subDialogSwitchEditState(isEdit);
        this.classifyAdapter.setEdit(isEdit);
        /* 编辑完成回调重排序 */
        if(!isEdit && this.actionHappenedListener != null){
            this.actionHappenedListener.dataSorted(classifyData);
        }
    }

    public boolean getEditState(){
        return this.isEdit;
    }

    @Override
    protected Dialog createSubDialog() {
        subDialog = new ExperienceSubDialog(getContext());
        subDialog.setDialogActionDownListener(this);
        subDialog.setDialogDismissListener(new ExperienceSubDialog.DialogDismissListener() {
            @Override
            public void onDismiss() {
                if(!isEdit){
                    List<TiyanApps> groupData = classifyData.get(subDialog.getParentPosition());
                    TiyanApps lastApp = groupData.get(groupData.size()-1);
                    if(lastApp.getPid().equals("add"))
                        groupData.remove(lastApp);
                    return;
                }
                if(subTitleEdit == null)
                    return;
                if(subTitleEdit.getText().toString().trim().length() == 0)
                    subTitleEdit.setText((String)subTitleEdit.getTag());
                if(subTitleEdit.isFocused())
                    subTitleEdit.clearFocus();
                renameGroup();
            }
        });
        return subDialog;
    }

    @Override
    protected View getSubContent() {
        this.subContentView = inflate(getContext(), R.layout.experience_sub_content, null);
        this.subTitleContent = (TextView) subContentView.findViewById(R.id.experience_sub_title_content);
        this.subTitleEdit = (EditText) subContentView.findViewById(R.id.experience_sub_title_edit);
        this.subGroupDelete = (ImageView) subContentView.findViewById(R.id.experience_sub_group_delete);
        this.subEditView = (LinearLayout) subContentView.findViewById(R.id.experience_sub_edit);
        this.subEditSelete = (TextView) subContentView.findViewById(R.id.experience_sub_edit_select);
        this.subEditRemove = (TextView) subContentView.findViewById(R.id.experience_sub_edit_remove);
        this.subEditDelete = (TextView) subContentView.findViewById(R.id.experience_sub_edit_delete);
        this.subGroupDelete.setOnClickListener(this);
        this.subEditSelete.setOnClickListener(this);
        this.subEditRemove.setOnClickListener(this);
        this.subEditDelete.setOnClickListener(this);
        this.subTitleEdit.setTag("新建组");
        this.subTitleEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE)
                    onDialogActionDown(subTitleEdit.getX(), subTitleEdit.getY());
                return true;
            }
        });
        return this.subContentView;
    }

    @Override
    public void onSubDialogShow(Dialog dialog, int parentPosition) {
        subDialog.setParentPosition(parentPosition);
        subDialog.setGroupId(classifyData.get(parentPosition).get(0).getGid());
        TiyanApps lastApp = classifyData.get(parentPosition).get(classifyData.get(parentPosition).size()-1);
        if(!isEdit && !"add".equals(lastApp.getPid())) {
            TiyanApps addApp = new TiyanApps();
            addApp.setPName("添加");
            addApp.setPid("add");
            classifyData.get(parentPosition).add(addApp);
        }
        if(subRecyclerView == null){
            subRecyclerView = getSubRecyclerView();
            subRecyclerView.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if(event.getAction() == MotionEvent.ACTION_DOWN)
                        onDialogActionDown(event.getX(), event.getY());
                    return false;
                }
            });
        }
        subRecyclerView.scrollToPosition(0);
        subDialogSwitchEditState(isEdit);
    }

    private void subDialogSwitchEditState(boolean isEdit){
        if(classifyData.size()-1 < subDialog.getParentPosition()) {
            subDialog.setParentPosition(0);
            if (classifyData.size() == 0)
                return;
        }
        if(isEdit){
            subTitleEdit.setText(classifyData.get(subDialog.getParentPosition()).get(0).getGName());
            subTitleEdit.setTag(subTitleEdit.getText().toString());
            subTitleEdit.setHint(subTitleEdit.getText().toString());
            subTitleEdit.setVisibility(VISIBLE);
            if(subTitleEdit.isFocused())
                subTitleEdit.clearFocus();
            subTitleContent.setVisibility(GONE);
            subGroupDelete.setVisibility(VISIBLE);
            subEditView.setVisibility(VISIBLE);
            for(TiyanApps apps : classifyData.get(subDialog.getParentPosition())){
                if(!apps.getIsCheck()){
                    onAllItemCheck(false);
                    return;
                }
            }
            onAllItemCheck(true);
        } else{
            subTitleContent.setText(classifyData.get(subDialog.getParentPosition()).get(0).getGName());
            subTitleContent.setVisibility(VISIBLE);
            subTitleEdit.setVisibility(GONE);
            subGroupDelete.setVisibility(GONE);
            subEditView.setVisibility(GONE);
        }
    }

    @Override
    public void onClick(View v) {
        onDialogActionDown(v.getX(), v.getY());
        switch (v.getId()){
            case R.id.experience_sub_group_delete:
                showRemindDialog("是否删除该组以及组内全部应用？", v.getId());
                break;
            case R.id.experience_sub_edit_select:
                onAllItemCheck(!allSubItemCheck);
                for (TiyanApps apps : classifyData.get(subDialog.getParentPosition()))
                    apps.setIsCheck(allSubItemCheck);
                classifyAdapter.getSubAdapter().notifyDataSetChanged();
                classifyAdapter.getMainAdapter().notifyItemChanged(subDialog.getParentPosition());
                break;
            case R.id.experience_sub_edit_remove:
                showRemindDialog("是否将选中应用移出组？", v.getId());
                break;
            case R.id.experience_sub_edit_delete:
                showRemindDialog("是否删除选中应用？", v.getId());
                break;
            case R.id.right_btn:
                remindDialogClick(subDialog.getParentPosition());
                break;
        }
    }

    private CommDialog remindDialog;
    private void showRemindDialog(String content, int viewId){
        if(remindDialog == null) {
            remindDialog = new CommDialog(getContext());
            remindDialog.setRightListener(this);
        }
        boolean hasIconCheck = false;
        for(TiyanApps apps : classifyData.get(subDialog.getParentPosition())){
            if(apps.getIsCheck()){
                hasIconCheck = true;
                break;
            }
        }
        if(hasIconCheck || viewId == R.id.experience_sub_group_delete){
            remindDialog.setContent(content);
            remindDialog.setTag(viewId);
            remindDialog.show();
        }
    }

    private void remindDialogClick(int parentPosition){
        int viewId = (int) remindDialog.getTag();
        if(viewId == R.id.experience_sub_group_delete){             // 删除组
            subDialog.dismiss();
            List<TiyanApps> deleteGroup = classifyData.remove(parentPosition);
            classifyAdapter.getMainAdapter().notifyItemRemoved(parentPosition);
            /* 删除组回调 */
            if(this.actionHappenedListener != null) {
                ArrayList<String> deleteGroupId = new ArrayList<>();
                deleteGroupId.add(deleteGroup.get(0).getParentMid());
                this.actionHappenedListener.dataDelete(deleteGroupId);
            }
        } else{
            List<TiyanApps> groupData = classifyData.get(parentPosition);
            List<TiyanApps> checkDatas = new ArrayList<>();
            for (TiyanApps apps : groupData)
                if (apps.getIsCheck())
                    checkDatas.add(apps);
            for (TiyanApps apps : checkDatas)
                groupData.remove(apps);
            if(viewId == R.id.experience_sub_edit_remove){          // 将应用移出组
                List<List<TiyanApps>> removeData = new ArrayList<>();
                for(TiyanApps apps : checkDatas){
                    List<TiyanApps> app = new ArrayList<>();
                    app.add(apps);
                    removeData.add(app);
                }
                classifyData.addAll(parentPosition+1, removeData);
                if(groupData.size() == 0)
                    classifyData.remove(parentPosition);
                /* 应用出组回调 */
                if(this.actionHappenedListener != null) {
                    List<String> moveOutDatasId = new ArrayList<>();
                    for (TiyanApps moveOutData : checkDatas)
                        moveOutDatasId.add(moveOutData.getMid());
                    this.actionHappenedListener.iconsMoveOut(moveOutDatasId, subDialog.getGroupId());
                }
            } else if(viewId == R.id.experience_sub_edit_delete) {  // 删除组内选择应用
                /* 应用删除回调 */
                if(this.actionHappenedListener != null) {
                    List<String> deleteDatasId = new ArrayList<>();
                    for (TiyanApps deleteDataId : checkDatas)
                        deleteDatasId.add(deleteDataId.getMid());
                    this.actionHappenedListener.dataDelete(deleteDatasId);
                }
            }
            // 更新视图
            if (groupData.size() > 1) {
                classifyAdapter.getSubAdapter().notifyDataSetChanged();
            } else {
                subDialog.dismiss();
                if(viewId == R.id.experience_sub_edit_delete) {
                    if (groupData.size() == 1) {
                        classifyAdapter.notifyItemChanged(parentPosition);
                    } else {
                        classifyData.remove(parentPosition);
                        classifyAdapter.getMainAdapter().notifyItemRemoved(parentPosition);
                    }
                    return;
                }
            }
            classifyAdapter.getMainAdapter().notifyDataSetChanged();
        }
    }

    /* 组重命名 */
    private void renameGroup(){
        if(!isEdit || classifyData.get(subDialog.getParentPosition()) == null
                || classifyData.get(subDialog.getParentPosition()).size() <= 0
                || subTitleEdit.getText().toString().equals(classifyData.get(subDialog.getParentPosition()).get(0).getGName()))
            return;
        for(TiyanApps apps : classifyData.get(subDialog.getParentPosition()))
            apps.setGName(subTitleEdit.getText().toString());
        classifyAdapter.getMainAdapter().notifyItemChanged(subDialog.getParentPosition());
        /* 组重命名回调 */
        if(this.actionHappenedListener != null)
            this.actionHappenedListener.groupRename(subTitleEdit.getText().toString(), subDialog.getGroupId());
    }

    /* 删除全部选中的图标 */
    public void deleteAllCheckIcon(){
        List<TiyanApps> checkIcons = removeAllCheckIcon();
        classifyAdapter.notifyDataSetChanged();
        /* 应用删除回调 */
        if(this.actionHappenedListener != null){
            List<String> deleteIconIds = new ArrayList<>();
            for(TiyanApps deleteApp : checkIcons)
                deleteIconIds.add(deleteApp.getMid());
            this.actionHappenedListener.dataDelete(deleteIconIds);
        }
    }

    /* 合并全部选中的图标为新组 */
    public void mergeAllCheckIcon(String groupName){
        List<TiyanApps> checkIcons = getAllCheckIcon();
        for(TiyanApps checkIcon : checkIcons)
            checkIcon.setGName(groupName);
        int firstCheckIconPosition = getFirstCheckIconPosition();
        removeAllCheckIcon();
        classifyData.add(firstCheckIconPosition, checkIcons);
        classifyAdapter.notifyDataSetChanged();
        /* 创建组回调 */
        if(this.actionHappenedListener != null){
            this.actionHappenedListener.groupCreated(classifyData.get(firstCheckIconPosition));
        }
    }

    /* 移动全部选中的图标到组 */
    public void moveAllCheckIconToGroup(int groupPosition){
        List<TiyanApps> checkIcons = getAllCheckIcon();
        String groupName = classifyData.get(groupPosition).get(0).getGName();
        String groupId = classifyData.get(groupPosition).get(0).getGid();
        String groupMid = classifyData.get(groupPosition).get(0).getParentMid();
        boolean allGroupIconChecked = true;
        for(TiyanApps groupIcon : classifyData.get(groupPosition)) {
            if (!groupIcon.getIsCheck()) {
                allGroupIconChecked = false;
                break;
            }
        }
        removeAllCheckIcon();
        for(int i = 0; i < classifyData.size(); i++){
            List<TiyanApps> groupData = classifyData.get(i);
            if(groupId == null)
                break;
            if(groupId.equals(groupData.get(0).getGid())){
                groupPosition = i;
                break;
            }
        }
        if(allGroupIconChecked)
            classifyData.add(groupPosition, new ArrayList<TiyanApps>());
        List<String> checkIconIds = new ArrayList<>();
        for(TiyanApps checkIcon : checkIcons) {
            checkIcon.setGName(groupName);
            checkIcon.setGid(groupId);
            checkIcon.setParentMid(groupMid);
            classifyData.get(groupPosition).add(checkIcon);
            checkIconIds.add(checkIcon.getMid());
        }
        classifyAdapter.notifyDataSetChanged();
        /* 应用入组回调 */
        if(this.actionHappenedListener != null){
            this.actionHappenedListener.iconsMoveIn(checkIconIds, groupId);
        }
    }

    /* 获取被选中图标的个数 */
    public int getIconCheckNum(){
        int checkNum = 0;
        if(classifyData == null)
            return checkNum;
        for(List<TiyanApps> groupDatas : classifyData)
            for(TiyanApps apps : groupDatas)
                if(apps.getIsCheck())
                    checkNum++;
        return checkNum;
    }

    /* 获取第一个选中 icon 的坐标 */
    public int getFirstCheckIconPosition(){
        for(int i = 0; i < classifyData.size(); i++){
            for(int j = 0; j < classifyData.get(i).size(); j++){
                if(classifyData.get(i).get(j).getIsCheck())
                    return i;
            }
        }
        return -1;
    }

    /* 获取全部选中的图标 */
    public List<TiyanApps> getAllCheckIcon(){
        if(classifyData == null)
            return null;
        List<TiyanApps> checkIcons = new ArrayList<>();
        for(List<TiyanApps> groupDatas : classifyData)
            for(TiyanApps apps : groupDatas)
                if(apps.getIsCheck())
                    checkIcons.add(apps);
        return checkIcons;
    }

    /* 删除全部选中图标 */
    public List<TiyanApps> removeAllCheckIcon(){
        List<TiyanApps> checkIcons = new ArrayList<>();
        for(List<TiyanApps> groupDatas : classifyData)
            for (TiyanApps groupIcon : groupDatas)
                if(groupIcon.getIsCheck())
                    checkIcons.add(groupIcon);
        for(TiyanApps checkIcon : checkIcons)
            for (List<TiyanApps> groupData : classifyData)
                if(groupData.remove(checkIcon))
                    break;
        List<List<TiyanApps>> emptyLists = new ArrayList<>();
        for(List<TiyanApps> groupDatas : classifyData)
            if(groupDatas.size() == 0)
                emptyLists.add(groupDatas);
        for(List<TiyanApps> emptyList : emptyLists)
            classifyData.remove(emptyList);
        return checkIcons;
    }

    /* 获取所有组的坐标 */
    public List<Integer> getAllGroupPosition(){
        List<Integer> allGroupPosition = new ArrayList<>();
        for(int i = 0; i < classifyData.size(); i++)
            if(classifyData.get(i).size() > 1)
                allGroupPosition.add(i);
        return allGroupPosition;
    }

    /* 次级对话框触摸回调 */
    @Override
    public void onDialogActionDown(float x, float y) {
        if(isEdit && subTitleEdit != null && subTitleEdit.isFocused()){
            if(subTitleEdit.getText().toString().trim().length() == 0)
                subTitleEdit.setText((String)subTitleEdit.getTag());
            MyUtil.closeKeyword(getContext(), subTitleEdit);
            renameGroup();
        } else if(x < subContentView.getX() || x > subContentView.getX()+subContentView.getWidth()
                || y < subContentView.getY() || y > subContentView.getY()+subContentView.getHeight()){
            subDialog.dismiss();
        }
    }

    /* 组内全选回调 */
    private boolean allSubItemCheck;
    @Override
    public void onAllItemCheck(boolean isAllItemCheck) {
        if(allSubItemCheck == isAllItemCheck)
            return;
        allSubItemCheck = isAllItemCheck;
        subEditSelete.setText(allSubItemCheck ? "反选" : "全选");
    }

    /* 普通状态切换到编辑状态回调 */
    @Override
    public void switchToEdit() {
        setEdit(true);
    }

    /* 图标单击回调 */
    @Override
    public void onIconClick(int parentIndex, int index) {
//        if(classifyData.get(parentIndex).size() > 1)
//            subDialog.dismiss();
        if(this.iconClickListener != null)
            this.iconClickListener.onIconClick(parentIndex, index);
    }

    /* 组创建回调 */
    @Override
    public void groupCreated(List<TiyanApps> groupData) {
        if(this.actionHappenedListener != null)
            this.actionHappenedListener.groupCreated(groupData);
    }

    /* 图标进组回调 */
    @Override
    public void iconsMoveIn(List<String> iconsId, String groupId) {
        if(this.actionHappenedListener != null)
            this.actionHappenedListener.iconsMoveIn(iconsId, groupId);
    }

    /* 图标出组回调 */
    @Override
    public void iconsMoveOut(List<String> iconsId, String groupId) {
        if(this.actionHappenedListener != null)
            this.actionHappenedListener.iconsMoveOut(iconsId, groupId);
    }

    /* 图标单击监听器 */
    private IconClickListener iconClickListener;
    public void setIconClickListener(IconClickListener iconClickListener){
        this.iconClickListener = iconClickListener;
    }

    public interface IconClickListener{
        void onIconClick(int parentIndex, int index);
    }

    /* 切换编辑状态监听器 */
    private EditStateChangeListener editStateChangeListener;
    public void setEditStateChangeListener(EditStateChangeListener editStateChangeListener){
        this.editStateChangeListener = editStateChangeListener;
    }
    public interface EditStateChangeListener{
        void onEditStateChange(boolean isEdit);
    }

    /* 数据集更新回调 */
    private NotifyDataSetChangedListener notifyDataSetChangedListener;
    public void setNotifyDataSetChangedListener(NotifyDataSetChangedListener listener){
        this.notifyDataSetChangedListener = listener;
    }
    public interface NotifyDataSetChangedListener{
        void onDataSetChanged(List<List<TiyanApps>> classifyData);
    }

    /* 事件监听器 */
    private ActionHappenedListener actionHappenedListener;
    public void setActionHappenedListener(ActionHappenedListener actionHappenedListener){
        this.actionHappenedListener = actionHappenedListener;
    }
    public interface ActionHappenedListener{
        void groupCreated(List<TiyanApps> groupData);           // 组创建回调
        void groupRename(String name, String groupId);          // 组重命名回调
        void iconsMoveIn(List<String> iconsId, String groupId); // 图标进组回调
        void iconsMoveOut(List<String> iconsId, String groupId);// 图标出组回调
        void dataDelete(List<String> mids);                     // 应用删除回调
        void dataSorted(List<List<TiyanApps>> data);            // 应用排序回调
    }
}